package com.supor.aiot.home.ui.device.config;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.WindowManager;

import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.RxTimerUtil;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.utils.Util;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.common.helper.WifiStationManager;
import com.supor.aiot.home.R;
import com.supor.aiot.home.databinding.ActivityNfcApGuideBinding;
import com.supor.aiot.home.helper.DataCache;
import com.supor.nfc.lib.utils.NfcUtils;

import static com.supor.aiot.common.app.Constants.REQUEST_CODE;
import static com.supor.aiot.common.app.Constants.SETTING_AP;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: NFC热点配网引导页 <br>
 * 作者: lei <br>
 * 日期: 2020/12/8 <br>
 */
public class NFCApGuideActivity extends BaseConfigActivity<NoViewModel, ActivityNfcApGuideBinding> {

    private AppBasicDialog failureDialog;
    String ssid = null;
    String bssid = null;
    String pass = null;
    boolean isApMode = false;
    private ProductType.ProductModel productModel;
    /**
     * 三个步骤，默认页面为第一个步骤，点了下一步为第二个步骤，点了取消为第三个步骤
     */
    int step = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int resourceId() {
        return R.layout.activity_nfc_ap_guide;
    }

    @Override
    public void initData() {
        super.initData();
        Intent intent = getIntent();
        if (intent != null) {
            productModel = (ProductType.ProductModel) intent.getSerializableExtra(Constants.Key.PRODUCT_MODEL);
            if (productModel == null) {
                Logc.d(TAG, "iotDevice is null");
                finish();
            }
        }
    }

    public void initView() {
        super.initView();
        bindingView.setViewM(this);
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            ssid = bundle.getString(Constants.Key.SSID);
            bssid = bundle.getString(Constants.Key.BSSID);
            pass = bundle.getString(Constants.Key.PASS);
            Logc.i("NFC ssid= " + ssid + ", bssid= " + bssid + ", pass= " + pass);
        }

        // 点击下方【去开启手机热点】，注意不要使用5GHz模式
        String tip = getString(R.string.bind_nfc_ap_guide_step1);
        SpannableString ss = new SpannableString(tip);

        ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("个人热点") - 1, tip.indexOf("个人热点") + 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bindingView.tvTextStep1.setText(ss);

        try {
            bindingView.bindWifiMain.etPassword.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (Util.hasChineseChar(s.toString())) {
                        tips(getResources().getString(R.string.bind_wifi_pass_no_chinese));
                        bindingView.btnNextStep.setEnabled(false);
                    } else {
                        bindingView.btnNextStep.setEnabled(true);
                    }
                    if (s.length() >= 8) {
                        bindingView.btnNextStep.setEnabled(true);
                    } else {
                        bindingView.btnNextStep.setEnabled(false);
                    }
                    // if (!isApMode) {
                    //     bindingView.btnNextStep.setEnabled(false);
                    // }
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });
            bindingView.bindWifiMain.etPassword.setFilters(new InputFilter[]{
                    (source, start, end, dest, dstart, dend) -> {
                        if (Util.hasChineseChar(source.toString())) {
                            tips(getResources().getString(R.string.bind_wifi_pass_no_chinese));
                            return "";
                        } else
                            return source;
                    }
            });

        } catch (Exception e) {
            e.printStackTrace();
            tips(e.getMessage());
        }

        bindingView.bindWifiMain.cbHidePass.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                //选择状态 显示明文--设置为可见的密码
                //mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                //第二种
                bindingView.bindWifiMain.etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType
                // .TYPE_TEXT_VARIATION_PASSWORD
                //mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType
                // .TYPE_TEXT_VARIATION_PASSWORD);
                //第二种
                bindingView.bindWifiMain.etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            Util.setEditTextCursorEnd(bindingView.bindWifiMain.etPassword);

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initApView();
        startTimer();
    }

    /**
     * 开始定时
     */
    public void startTimer() {
        RxTimerUtil.interval(2000, next -> {
            Logc.i("startTimer: next: " + next);
            boolean apMode = WifiStationManager.isWifiApOpen(this);
            if (isApMode != apMode) {
                initApView(apMode);
            }
        });
    }

    /**
     * 停止定时
     */
    public void stopTimer() {
        RxTimerUtil.cancelInterval();
    }

    private void initApView() {
        isApMode = WifiStationManager.isWifiApOpen(this);
        initApView(isApMode);
    }

    private void initApView(boolean isApMode) {
        this.isApMode = isApMode;
        Logc.i("updateNetStatus: ap: " + isApMode);
        if ((isApMode || step == 2) && step != 0) {
            step = 2;
            bindingView.llNfcTip.setVisibility(View.GONE);
            bindingView.bindWifiMain.rlRoot.setVisibility(View.VISIBLE);
            bindingView.bindWifiMain.ivSsid.setImageResource(R.mipmap.bind_ap_wifi_ssid);
            bindingView.bindWifiMain.tvSsidSetting.setVisibility(View.GONE);
            bindingView.bindWifiMain.etSsid.setHint(R.string.bind_input_ap_ssid);
            bindingView.bindWifiMain.etPassword.setHint(R.string.bind_input_ap_pass);
            bindingView.ivApGuide.setVisibility(View.GONE);
            bindingView.ivApGuide1.setVisibility(View.VISIBLE);
            bindingView.tvAp.setVisibility(View.GONE);
            if (TextUtils.isEmpty(bindingView.bindWifiMain.etSsid.getInputText())
                    || TextUtils.isEmpty(bindingView.bindWifiMain.etPassword.getInputText())) {
                bindingView.btnNextStep.setEnabled(false);
            }
        } else {
            step = 1;
            bindingView.btnNextStep.setEnabled(true);
            bindingView.llNfcTip.setVisibility(View.VISIBLE);
            bindingView.bindWifiMain.rlRoot.setVisibility(View.GONE);
            bindingView.ivApGuide.setVisibility(View.VISIBLE);
            bindingView.ivApGuide1.setVisibility(View.GONE);
            bindingView.tvAp.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopTimer();
        if (NfcUtils.mNfcAdapter != null) {
            NfcUtils.mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    public void updateNetStatus(int type) {
        super.updateNetStatus(type);
        initApView();
    }

    @Override
    public void updateNFCStatus(int state) {
        super.updateNFCStatus(state);
        NfcUtils.init(this);
        NfcUtils.configNfc(this);
    }

    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_next_step) {
            if (step == 1) {
                step = 2;
                initApView();
            } else if (isApMode || step == 2) {
                String ssid = bindingView.bindWifiMain.etSsid.getInputText();
                if (ssid.length() < 1) {
                    tips(getResources().getString(R.string.bind_wifi_ssid_not_over_0));
                    return;
                }
                if (Util.hasChineseChar(ssid)) {
                    tips(getResources().getString(R.string.bind_wifi_ssid_no_chinese));
                    return ;
                }
                pass = bindingView.bindWifiMain.etPassword.getInputText();
                if (Util.hasChineseChar(pass)) {
                    tips(getResources().getString(R.string.bind_wifi_pass_no_chinese));
                    return;
                } else if (pass.length() > 0 && pass.length() < 8) {
                    tips(getResources().getString(R.string.bind_wifi_pass_not_over_8));
                    return;
                }
                Bundle bundle = getIntent().getExtras();
                if (bundle == null) {
                    bundle = new Bundle();
                }

                // Logc.e("input routerSsid= " + ssid + ", routerPwd= " + pass);
                bundle.putString(Constants.Key.SSID, ssid);
                bundle.putString(Constants.Key.PASS, pass);
                String bssid = WifiStationManager.getInstance().getCurrentWifiBSSID();
                Util.isValidMac(bssid);
                if (bssid != null) {
                    bundle.putString(Constants.Key.BSSID, bssid.replace(":", ""));
                }
                DataCache.CURRENT_SSID = ssid;
                DataCache.CURRENT_PWD = pass;

                Intent intent;
                int type = bundle.getInt(Constants.Key.CONFIG_TYPE, -1);
                if (type == 0 || NfcUtils.NFC_STATE != 1) { // todo
                    bundle.putInt(Constants.Key.CONFIG_TYPE, 0);
                    intent = new Intent(this, NFCGuideActivity.class);
                } else {
                    ToastUtils.getInstance().showCustomToast("暂不支持");
                    return;
                }
                bundle.putInt(Constants.Key.CONFIG_TYPE, 2);
                intent.putExtra(Constants.Key.PRODUCT_MODEL, productModel);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE);
            }
        } else if (id == R.id.btn_cancel) {
            if (step == 2) {
                step = 0;
                initApView();
                return;
            }
            finish();
        } else if (id == R.id.tv_ap) {
            ActivityHelper.gotoApSetting(this, SETTING_AP);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NfcUtils.mNfcAdapter = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Constants.SETTING_AP == requestCode) {
            boolean isApOpen = WifiStationManager.isWifiApOpen(this);
            Logc.e("onActivityResult: ap: " + isApOpen);
            // if (isApOpen) {
            //     setResult(Constants.RESULT_CODE);
            // } else {
            //     setResult(-1);
            // }
            // finish();
        } else if (Constants.REQUEST_CODE == requestCode) {
            if (resultCode == 1) {
                bindingView.bindWifiMain.cbHidePass.setChecked(true);
            }
        }
    }
}
